package com.zy.levelcache.decoration.up;

import com.zy.levelcache.decoration.ComponentCache;
import com.zy.levelcache.decoration.basic.JvmComponentCache;
import com.zy.levelcache.decoration.connection.RedisCheckConnection;
import com.zy.levelcache.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName RedisDecorate
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
@Slf4j
@Component
public class RedisDecorate implements ComponentCache {

    @Autowired
    private JvmComponentCache jvmComponentCache;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisCheckConnection redisCheckConnection;



    /***
     * 是否开启了二级缓存
     */
    public static volatile boolean IS_OPENG_REDIS = true;

    @Override
    public <T> T getCache(String key, Class<T> returnClass, ProceedingJoinPoint joinPoint) {
        T redisUser = null;
        if (!IS_OPENG_REDIS) {
            return jvmComponentCache.getCache(key, returnClass, joinPoint);
        }

        // 查询我们的二级缓存
        try {
            redisUser = redisUtils.getEntity(key, returnClass);
        } catch (Exception e) {
            IS_OPENG_REDIS = false;
            //Async PING
            redisCheckConnection.ping();
            e.printStackTrace();
        }

        if (redisUser != null) {
            return (T) redisUser;
        }

        // 如果一级缓存存在数据
        T jvmUser = jvmComponentCache.getCache(key, returnClass, joinPoint);
        if (jvmUser == null) {
            return null;
        }
        // 将该缓存数据放入到二级缓存中
        redisUtils.putEntity(key, jvmUser);
        return (T) jvmUser;
    }



}
